package com.rmb.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.rmb.common.exception.CustomException;
import com.rmb.common.exception.ExceptionCast;
import com.rmb.common.model.response.CommonCode;
import com.rmb.common.model.response.ResponseResult;
import com.rmb.entity.EtlDataEngineVoResult;
import com.rmb.entity.result.EngIneCode;
import com.rmb.mapper.EtlDataEngineMapper;
import com.rmb.entity.EtlDataEngine;
import com.rmb.service.EtlDataEngineService;
import com.rmb.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import com.rmb.common.model.response.ResponseResult;
import org.springframework.test.annotation.Rollback;
import org.springframework.transaction.annotation.Transactional;

/**
 * (EtlDataEngine)表服务实现类
 *
 * @author makejava
 * @since 2021-01-13 10:24:40
 */
@Service("etlDataEngineService")
@Transactional(rollbackFor = Exception.class)
public class EtlDataEngineServiceImpl implements EtlDataEngineService {

    private static final Integer MANPAGE = 100;

    @Resource
    private EtlDataEngineMapper etlDataEngineMapper;

    @Resource
    IdWorker idWorker;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public EtlDataEngine queryById(Long id) {
        return this.etlDataEngineMapper.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<EtlDataEngine> queryAllByLimit(int offset, int limit) {
        return this.etlDataEngineMapper.queryAllByLimit(offset, limit);
    }


    /**
     * 新增数据
     * @param etlDataEngine 实例对象
     * @return 实例对象
     */
    @Override
    public EtlDataEngine insert(EtlDataEngine etlDataEngine) {
        //任务类型id不能为空
        Long engineTypeId = etlDataEngine.getEngineTypeId();
        if(StringUtils.isNull(engineTypeId)){
            ExceptionCast.cast(CommonCode.PARAM_FALL);
        }
        //uuid生成
        String sub = UUID.randomUUID().toString();
        String clName = "etl"+sub.substring(0, 4);
        //检查引擎名称或者函数名是够存在
        String engineName = etlDataEngine.getEngineName();
        EtlDataEngine ec = etlDataEngineMapper.classAndEngine(clName, engineName);
        if(StringUtils.isNotNull(ec)){
            ExceptionCast.cast(EngIneCode.THE_DATA_ENGINE_EXISTS);
        }
        //编译类方法
        String engineCode = null;
        try {
            engineCode = CompileUtil.addEngIneCode(clName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //纳入对象
        etlDataEngine.setId(idWorker.nextId());
        etlDataEngine.setClName(clName);
        etlDataEngine.setEngineCode(engineCode);
        //添加方法
        etlDataEngineMapper.insert(etlDataEngine);
        return etlDataEngine;
    }

    /**
     * 根据ID请求数据
     * @param id id
     * @return getEngineId
     */
    @Override
    public EtlDataEngine getEngineId(Long id) {
        return this.etlDataEngineMapper.getEngineId(id);
    }

    /**
     * 编译代码
     * @param id id
     * @param compileJava 数据代码
     * @return compile
     */
    @Override
    public ResponseResult compile(Long id, String compileJava) {
        EtlDataEngine etlDataEngine = getEngineId(id);
        String className = etlDataEngine.getClName();
        String code = "";
        try {
            code = CompileUtil.updateEngineCode(className, compileJava);
        } catch (Exception e) {
            e.printStackTrace();
        }
        etlDataEngine.setId(id);
        etlDataEngine.setEngineCode(code);
        boolean updateCompile = etlDataEngineMapper.updateCompile(etlDataEngine);
        if(!updateCompile){
            ExceptionCast.cast(CommonCode.FAIL);
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    @Override
    public ResponseResult deleteById(Long id) {
        EtlDataEngine etlDataEngine = etlDataEngineMapper.queryById(id);
        //删除Java文件
        boolean delete = FileUtil.deleteJava(etlDataEngine.getClName());
        //删除class文件
        boolean deleteClass = FileUtil.deleteclass(etlDataEngine.getClName());
        if (delete && deleteClass){
            // system.ge ：回收不再被引用的对象的内存空间。
            System.gc();
            System.out.println("删除成功！！");
        }else{
            System.out.println("删除失败！！");
        }
        int i = this.etlDataEngineMapper.deleteById(id);
        if (i > 0){
            return ResponseResult.methodSuccess();
        }
        return ResponseResult.methodFail();
    }



    /**
     *  查询所有
     *   模糊
     * @param page 查询起始位置
     * @param size 查询条数
     * @param engineName 引擎名称
     * @param engineTypeId 引擎ID
     * @param codeType 类型
     * @return selectEtlEngine
     */
    @Override
    public List<EtlDataEngineVoResult> list(int page, int size, String engineName, String engineTypeId, String codeType) {
        if (size> MANPAGE){
            size = MANPAGE;
        }

        return etlDataEngineMapper.selectEtlEngine(page,size,engineName, engineTypeId, codeType);
    }

    /**
     * 修改方法 不修改代码
     * @param etlDataEngine 数据
     * @return Update
     */
    @Override
    public ResponseResult updateEtlDataEngine(EtlDataEngine etlDataEngine) {
        //根据id查询数据
        EtlDataEngine dataEngine = etlDataEngineMapper.queryById(etlDataEngine.getId());
        //查询数据个数
        int i = etlDataEngineMapper.selectNum(dataEngine.getEngineName());
        //判断引擎名称是否唯一
        if (i==1){

            EtlDataEngine engine = new EtlDataEngine();
            engine.setId(dataEngine.getId());
            engine.setEngineName(dataEngine.getEngineName());
            engine.setEngineTypeId(dataEngine.getEngineTypeId());
            engine.setCodeType(dataEngine.getCodeType());
            engine.setClName(dataEngine.getClName());
            engine.setRevision(dataEngine.getRevision());
            engine.setEngineCode(dataEngine.getEngineCode());
            //修改返回条数
            int i1 = etlDataEngineMapper.update(etlDataEngine);
            //判断是否执行成功  改变成功 1 不成功 0
            if (i1 == 1){
                return ResponseResult.methodSuccess();
            }
            return ResponseResult.methodFail();
        }
        return ResponseResult.methodFail();
    }

    /**
     * 根据ID回显编写代码模板
     * @param id id
     * @return 结果集
     */
    @Override
    public EtlDataEngine findById(Long id) {
        //判断ID是否为空
        if (id == null){
            ExceptionCast.cast(CommonCode.THIS_ID_NULL);
            return null;
        }
        //根据ID回显
        EtlDataEngine etlDataEngine = etlDataEngineMapper.findById(id);
        //判断对象是否为空
        if (etlDataEngine == null){
            ExceptionCast.cast(EngIneCode.THIS_OBJECT_ISNULL);
        }
        return etlDataEngine;
    }

    /**
     * 重新编写java代码
     * @param id id
     * @param javaString 前天传入的数据
     */
    @Override
    public int compileJava(Long id, String javaString) {

        //获取当前编写代码对象
        EtlDataEngine etlDataEngine = findById(id);

        int i = 0;

        /*重新生成编译*/
        try {
            String fileUtil = CreateFileUtil.updateFileUtil(etlDataEngine.getClName(), javaString);
            //更换引擎代码
            etlDataEngine.setEngineCode(fileUtil);
            //执行修改操作
            i = etlDataEngineMapper.compileJava(etlDataEngine);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return i;
    }


}